package net.newsmth.smthapp.android.ui;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import net.newsmth.smthapp.android.R;
import net.newsmth.smthapp.android.config.SmthConnection;
import net.newsmth.smthapp.android.config.SmthNetStatusType;
import net.newsmth.smthapp.android.helper.AccountHelperImpl;
import net.newsmth.smthapp.android.model.Account;
import net.newsmth.smthapp.android.widget.ErrorView;

public class LoginActivity extends BaseActivity implements
        Button.OnClickListener {
    public static String IS_AUTO_FINISH_KEY = "isAutoFinish";

    private TextView errorTextView;
    private EditText accountEditText;
    private EditText passwordEditText;
    private Button loginButton;

    private AccountHelperImpl accountHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        bindControl();
        this.accountHelper = new AccountHelperImpl(this.appSettings, this.connection);
        initUserName();
    }

    public void redirectToMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }



    private void bindControl() {
        accountEditText = (EditText)findViewById(R.id.account_edit_text);
        passwordEditText = (EditText)findViewById(R.id.password_edit_text);
        loginButton = (Button)findViewById(R.id.login_button);
        errorTextView = (TextView)findViewById(R.id.error_text);

        loginButton.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.login_button) {
            loginAndSave();
        }
    }

    //<editor-fold desc="UI Logic">
    private boolean isAutoFinish() {
        return getIntent().getBooleanExtra(IS_AUTO_FINISH_KEY, false);
    }

    private void finishActivity() {
        this.finish();
    }

    private String getUserName() {

        return this.accountEditText.getText().toString();
    }

    private String getPassword() {
        return this.passwordEditText.getText().toString();
    }

    public void showErrorText(String errorText) {
        this.errorTextView.setVisibility(View.VISIBLE);
        this.errorTextView.setText(errorText);
    }

    public void setUserName(String userName) {
        this.accountEditText.setText(userName);
    }

    public void setUserName(int resid) {
        this.accountEditText.setText(resid);
    }

    public void resetErrorText() {
        errorTextView.setText("");
        errorTextView.setVisibility(View.INVISIBLE);
    }
    //</editor-fold>

    //<editor-fold desc="Business Logic">
    private void initUserName() {
        Account account = accountHelper.loadAccount();
        setUserName(account.getUserName());
    }

    public AsyncTask<Account, Void, Boolean> loginAndSave() {
        resetErrorText();

        Account account = new Account();
        account.setUserName(getUserName());
        account.setPassword(getPassword());


        final AsyncTask<Account, Void, Boolean> task = new AsyncTask<Account, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Account... accounts) {
                return LoginActivity.this.accountHelper.loginAndSave(accounts[0]);
            }

            @Override
            protected void onPostExecute(Boolean result) {
                super.onPostExecute(result);

                if (result) {
                    if (isAutoFinish()) {
                        finishActivity();
                    } else {
                        redirectToMainActivity();
                    }
                }
            }
        };

        task.execute(account);

        return task;
    }

    @Override
    public Handler getNetworkHandler() {
        return new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (msg.what == SmthConnection.SMTH_NETWORK_HANDLER) {
                    Bundle data = msg.getData();
                    SmthNetStatusType statusType = SmthNetStatusType.valueOf(data.getString(
                            SmthConnection.SMTH_NETWORK_STATUS_TYPE_KEY));
                    String errorMessage = data.getString(SmthConnection.SMTH_NETWORK_Error_DESCRIPTION_KEY);

                    resetErrorText();

                    if (statusType != SmthNetStatusType.OK) {
//                        LoginActivityPresenter.this.loginActivity.showErrorText(
//                                TextCreatorUtil.getNetworkMessage(statusType, errorMessage));

                        showErrorText("登录失败");
                    }
                }
            }
        };
    }

    @Override
    protected ErrorView getGeneralErrorView() {
        return null;
    }
    //</editor-fold>


}
